<template>
  <el-cascader
    v-model="value"
    size="mini"
    :options="treeData"
    :props="props"
    separator="-"
    @change="changeValue"
  />
</template>

<script>
import { getDepartment } from '@/api/department'
import { transListToTree } from '@/utils'
export default {
  name: 'SelectTree',
  props: {
    departmentId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      value: null,
      treeData: [], // 赋值给级联组件的options
      props: {
        label: 'name', // 展示的文本
        value: 'id' // 存储的字段
      }
    }
  },
  watch: {
    departmentId: {
      immediate: true,
      handler(val) {
        this.value = val
      }
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      // 将组织架构的数据 转换为属性赋值给 treeDate
      this.treeData = transListToTree(await getDepartment(), 0)
    },
    changeValue(list) {
      // 取数组最后一位
      if (list.length > 0) {
        const res = list[list.length - 1]
        this.$emit('update:departmentId', res)
      } else {
        this.$emit('update:departmentId', null)
      }
    }
  }
}
</script>

<style scoped lang="scss">

</style>
